
# encoding: utf-8
import smtplib
import cfg

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import os

# TODO - logging
# TODO - attachment compression
# INFO - http://www.tutorialspoint.com/python/python_sending_email.htm

def send(to,subject='',body='',sender='',cc='',bcc='',files=[],images=[],html=True,charset="utf-8"):
	config = cfg.get('mail','mail')
	host = config['host']
	port = config.get('port',25)
	debug = config.get('debug',0)
	if not sender:
		sender = config['sender']
	server = smtplib.SMTP(host,port)
	if debug:
		server.set_debuglevel(1)
	msg = MIMEMultipart()
	msg['from'] = sender
	msg['to'] = to
	msg['subject'] = subject
	if cc:
		msg['cc'] = cc
	if bcc:
		msg['bcc'] = bcc
	if html:
		body_kind = "html"
	else:
		body_kind = "plain"
	msg.attach(MIMEText(body,body_kind,charset))
	for path in files:
		if path: 
			msg.attach(MIMEApplication(open(path,'rb').read(),name=os.path.split(path)[1]))
	for i,path in enumerate(images):
		if path:
			img = MIMEImage(open(path,'rb').read())
			img.add_header('Content-ID',"<image%d>"%(i+1))
			msg.attach(img)
	msg_str = msg.as_string()
	server.sendmail(sender, to.split(';')+cc.split(';')+bcc.split(';'), msg_str)
	server.quit()

if __name__=="__main__":
	pass
